package com.tcu.oss.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.tcu.config.MediaConfig;
import com.tcu.exception.SmartException;
import com.tcu.util.FileUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class AliyunOssImpl implements IOss{
    private MediaConfig config;

    @Autowired
    public void setConfig(MediaConfig config) {
        this.config = config;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String imgUrl="";
//        获取参数信息
        String endPoint = config.getEndPoint();
        String bucketName = config.getBucketName();
        String keyId = config.getKeyId();
        String keySecret = config.getKeySecret();
//        获取oss 客户端实例
        OSS client = new OSSClientBuilder().build(endPoint, keyId, keySecret);
        try {
            InputStream inputStream = file.getInputStream();
            String fileName = FileUtil.getFileName(file.getOriginalFilename());
            client.putObject(bucketName,fileName,inputStream);
            client.shutdown();
            imgUrl ="https://"+bucketName+"."+endPoint+"/"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new SmartException(20001,"图片上传发生异常");
        }

        return imgUrl;
    }

    @Override
    public Boolean deleteFileByFileName(String fileName) {
        //        获取参数信息
        String endPoint = config.getEndPoint();
        String bucketName = config.getBucketName();
        String keyId = config.getKeyId();
        String keySecret = config.getKeySecret();
        //        获取oss 客户端实例
        OSS client = new OSSClientBuilder().build(endPoint, keyId, keySecret);
        try {
            client.deleteObject(bucketName,fileName);
            client.shutdown();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmartException(20001,"删除失败！");
        }
    }
}
